package lesson3.example4;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.lang.instrument.ClassFileTransformer;
import java.lang.instrument.IllegalClassFormatException;
import java.security.ProtectionDomain;

import javassist.CannotCompileException;
import javassist.ClassPool;
import javassist.CtBehavior;
import javassist.CtClass;
import javassist.CtMethod;

public class SimpleClassTransformer implements ClassFileTransformer {
    @Override
    public byte[] transform(
    		ClassLoader loader, 
    		String className, 
    		Class<?> classBeingRedefined, 
    		ProtectionDomain protectionDomain, 
    		byte[] classfileBuffer) throws IllegalClassFormatException {
        try {
            if(!className.contains("example4")){
                return null;
            }
            CtClass ctClass = ClassPool.getDefault().makeClass(new ByteArrayInputStream(classfileBuffer));
            CtMethod[] declaredMethods = ctClass.getDeclaredMethods();
            for (CtBehavior method : declaredMethods) {
                method.insertBefore("System.out.println(\""+method.getLongName()+" before\");");
                method.insertAfter("System.out.println(\""+method.getLongName()+" end\");");
            }
            byte[] returnByte = ctClass.toBytecode();
            return returnByte;
        } catch (IOException e) {
            e.printStackTrace();
        } catch (CannotCompileException e) {
            e.printStackTrace();
        }
        return classfileBuffer;
    }
}